import { PublicKey, Connection, Transaction, SystemProgram, sendAndConfirmTransaction } from "@solana/web3.js";
import * as buffer from "buffer";
window.Buffer = buffer.Buffer;

const RPC = 'https://compatible-young-daylight.solana-mainnet.quiknode.pro/9300587c704a94a00e38e55a9b2f656d1d19b1e6/'

type PhantomEvent = "disconnect" | "connect" | "accountChanged";

interface ConnectOpts {
    onlyIfTrusted: boolean;
}
declare global {
    interface Window {
        Buffer: any; // whatever type you want to give. (any,number,float etc)
    }
  }
interface PhantomProvider {
    connect: (opts?: Partial<ConnectOpts>) => Promise<{ publicKey: PublicKey }>;
    disconnect: ()=>Promise<void>;
    on: (event: PhantomEvent, callback: (args:any)=>void) => void;
    isPhantom: boolean;
    signTransaction:any
}

type WindowWithSolana = Window & { 
    solana?: PhantomProvider
}

export async function connect() {
    const solWindow = window as WindowWithSolana
    if(!solWindow.solana) return {err: 'no wallet'}
    const kpair = await solWindow.solana.connect()
    return kpair.publicKey.toBase58()
}

export async function stake(amount: bigint) {
    const solWindow = window as WindowWithSolana
    if(!solWindow.solana) return {err: 'no wallet'}
    const wallet:any = await solWindow.solana.connect()
    const to = '32xeUzqpv7wgcJwLXhUyGo6EsTgzGzXizAW36anHCNDY'
    const toPubkey = new PublicKey(to)
    const connection = new Connection(RPC)
    const {blockhash} = await connection.getLatestBlockhash()
    const transaction = new Transaction({
        feePayer: wallet.publicKey,
        recentBlockhash: blockhash
    })
    window.Buffer = buffer.Buffer;

    transaction.add(
        SystemProgram.transfer({
        fromPubkey: wallet.publicKey,
        toPubkey,
        lamports: amount,
        })
    )

    const tx = await solWindow.solana.signTransaction(transaction);
    const id = await connection.sendRawTransaction(tx.serialize())
    return id
}

export async function gelSolBal() {
    const solWindow:any = window 
    if(!solWindow.solana) return {err: 'no wallet'}
    const wallet:any = await solWindow.solana.connect()
    const connection = new Connection(RPC)
    const bal = await connection.getBalance(wallet.publicKey)
    return bal / 1000_000_000
}
